package wqh.hk_server;

import cn.tpson.hk.core.HKDTServer;
import cn.tpson.hk.dto.HeartBeatReqMessage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import wqh.domain.HkServer;
import wqh.global.GlobalID;
import wqh.service.HkServerService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.sql.DriverManager;
import java.util.List;
import java.util.concurrent.SynchronousQueue;

/**
 * Created by devts on 2017/1/5.
 */
@WebServlet(name = "hkServlet")
public class HkServerServlet extends HttpServlet{

    @Override
    public void destroy() {
        super.destroy();
        HKDTServer.getInstance().stopServer();
        try {
            DriverManager.deregisterDriver(DriverManager.getDrivers().nextElement());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("海康数据传输启动#####################################");
        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:/spring/spring-data.xml","classpath:/spring/spring-beans.xml");
        HkServerCallBack hkServerCallBack = (HkServerCallBack) ac.getBean("hkServerCallBack");
        HKDTServer.getInstance().setCallBack(hkServerCallBack);
        HkServerService hkServerService = (HkServerService) ac.getBean("hkServerService");
        List<HkServer> hkServers = hkServerService.findAll();
        if(hkServers.size() != 0){
            for(HkServer h : hkServers){
                HKDTServer.getInstance().addServer(h.getIp(),h.getPort(),h.getConnection_try());
            }
        }

        GlobalID.addID("1024");
        GlobalID.addID("2048");
        GlobalID.addID("4096");

        Runnable runnable = () -> {
                try {
                    while (!Thread.currentThread().isInterrupted()){
                     if(GlobalID.getIDs().size() != 0){
                         for(String id : GlobalID.getIDs()){
                             HeartBeatReqMessage heartBeatReqMessage = new HeartBeatReqMessage();
                             heartBeatReqMessage.setHostId(id);
                             HKDTServer.getInstance().addMessage(heartBeatReqMessage);
                             System.out.println(id);
                             Thread.sleep(1000);
                         }
                     }
                    }
                }
                catch (Exception e) {
                   e.printStackTrace();
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
    }
}
